package com.hulushuju.core.security.ssl;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-05-21
 * @Desc: 域名确认者工厂类
 */
public class HostnameVerifierFactory {

    /**
     * 创建不校验直接返回true的HostnameVerifier
     *
     * @return TrustAllHostnameVerifier
     */
    public static HostnameVerifier createTrustAllVerifier() {
        return new TrustAllHostnameVerifier();
    }

    /**
     * 创建校验的HostnameVerifier
     *
     * @return TrustPartHostnameVerifier
     */
    public static HostnameVerifier createTrustPartVerifier() {
        return new TrustPartHostnameVerifier();
    }

    /**
     * 不管服务器主机名和请求url主机名是否相同,均返回true
     */
    private static class TrustAllHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    }

    /**
     * 校验服务器主机名和请求url主机名是否相同
     */
    private static class TrustPartHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession sslSession) {
            String serverHostname = sslSession.getPeerHost();
            return hostname.equals(serverHostname);
        }
    }
}